package com.eb.buybuybuy.service.impl;

import com.eb.buybuybuy.annotation.Autowired;
import com.eb.buybuybuy.annotation.Component;
import com.eb.buybuybuy.annotation.Service;
import com.eb.buybuybuy.bean.User;
import com.eb.buybuybuy.exception.PasswordIncorrectException;
import com.eb.buybuybuy.exception.UserNotFoundException;
import com.eb.buybuybuy.exception.UserRepeatException;
import com.eb.buybuybuy.mapper.UserMapper;
import com.eb.buybuybuy.service.UserService;

import javax.servlet.http.HttpSession;

@Component
@Service(proxyInterface = UserService.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User info(Integer id) throws Exception {
        User user = userMapper.getById(id);
        user.setPassword(null);
        return user;
    }

    @Override
    public void login(String username, String password, HttpSession session) throws Exception {
        User user = userMapper.getByUsername(username);
        if (user == null) {
            throw new UserNotFoundException();
        }
        if (!user.getPassword().equals(password)) {
            throw new PasswordIncorrectException();
        }
        session.setAttribute("userId", user.getId());
        session.setAttribute("username", user.getUsername());
    }

    @Override
    public void register(String username, String password, HttpSession session) throws Exception {
        User user = userMapper.getByUsername(username);
        if (user != null) {
            throw new UserRepeatException();
        }
        User newUser = new User(null, username, password);
        userMapper.insert(newUser);

        login(username, password, session);
    }

    @Override
    public void logout(HttpSession session) {
        session.invalidate();
    }
}
